import type { HttpError } from '@/utils/http/type'
import { ref } from 'vue'

interface Params {
  showLoading?: boolean
  manual?: boolean
  onSuccess?: (data: any) => void
  onError?: (error: HttpError['errData']) => void
  defaultParams?: any
}
export function useRequest<T extends (...args: any) => any>(service: any, options?: Params) {
  const loading = ref(false)
  const data = ref<ResData<T>>(null!)
  const optionsDefault = {
    manual: true,
    defaultParams: {},
    ...(options || {}),
  }

  const { manual } = optionsDefault
  const run = async (
    params?: Parameters<T>[0],
  ): Promise<{ type: 'success' | 'error' | 'locading', data?: any }> => {
    if (loading.value)
      return { type: 'locading' }
    loading.value = true
    // if (optionsDefault.showLoading) {}
    try {
      const res = await service(params)
      data.value = res
      optionsDefault?.onSuccess?.({
        type: 'success',
        data: res,
      })
      return {
        type: 'success',
        data: res,
      }
    }
    catch (error: any) {
      optionsDefault?.onError?.(error.errData as HttpError['errData'])
      // if (error.response.status === 401) {
      // }
      return {
        type: 'error',
        data: error.errData,
      }
    }
    finally {
      loading.value = false
    }
  }
  if (!manual)
    run(optionsDefault.defaultParams)
  return { run, loading, data }
}
